package com.sphd.Restaurant.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sphd.Restaurant.R;
import com.sphd.Restaurant.base.BaseActivity;
import com.sphd.Restaurant.infos.CardInfo;
import com.sphd.Restaurant.infos.IntegralInfo;
import com.sphd.Restaurant.infos.PromotionsInfo;
import com.sphd.Restaurant.infos.RestaurantInfo;
import com.sphd.Restaurant.infos.TopupInfo;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.RestaurantPageP;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.views.RestaurantPageView;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class RestaurantPageActivity extends BaseActivity implements RestaurantPageView {

    @BindView(R.id.backdrop)
    ImageView backdrop;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_callPhone)
    ImageView ivCallPhone;
    @BindView(R.id.tv_openTime)
    TextView tvOpenTime;
    @BindView(R.id.tv_DeliverMealsTime)
    TextView tvDeliverMealsTime;
    @BindView(R.id.tv_gotomoney)
    TextView tvGotomoney;
    @BindView(R.id.tv_gomoney)
    TextView tvGomoney;
    @BindView(R.id.ll_aboutmoney)
    LinearLayout llAboutmoney;
    @BindView(R.id.cardInfo_content)
    TextView cardInfoContent;
    @BindView(R.id.ll_isCoupon)
    LinearLayout llIsCoupon;
    @BindView(R.id.topupInfo_content)
    TextView topupInfoContent;
    @BindView(R.id.ll_isRecharge)
    LinearLayout llIsRecharge;
    @BindView(R.id.tv_offers)
    TextView tvOffers;
    @BindView(R.id.sale_layout)
    LinearLayout saleLayout;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.sorce_layout)
    LinearLayout sorceLayout;
    @BindView(R.id.content_restaurant_page)
    RelativeLayout contentRestaurantPage;
    @BindView(R.id.bt_Takeaway)
    TextView btTakeaway;
    @BindView(R.id.bt_shopfororder)
    TextView btShopfororder;
    Intent intent;
    boolean isJump = true;
    String cgid;
    RestaurantInfo restaurantInfo;
    Bundle bundle;
    List<CardInfo> cardInfos;
    List<IntegralInfo> integralInfos;
    List<TopupInfo> topupInfos;
    List<PromotionsInfo> promotionsInfos;
    RestaurantPageP restaurantPageP;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CALL_PHONE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant_page);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        restaurantPageP = new RestaurantPageP(this);
        intent = getIntent();
        bundle = intent.getExtras();
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            isJump = false;
            Uri uri = getIntent().getData();
            if (uri != null) {
                cgid = uri.getQueryParameter("cgid");
                addData();
                isJump=false;
            }
        } else {
            isJump = true;
            if (!bundle.getString(Constants.TAG).equals(MainActivity.class.getName())) {
                cgid = bundle.getString(Constants.CG_ID);
                addData();
            } else {
                restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constants.RESTAURANT);
                cgid = String.valueOf(restaurantInfo.getId());
                initMessage();
            }
            toolbar.setNavigationOnClickListener(view -> AppManager.getAppManager().finishActivity(RestaurantPageActivity.class));
        }

    }

    private void initMessage() {
        setToolBar(toolbar, "", true);
        setImage(backdrop, restaurantInfo.getCg_pic());
        collapsingToolbar.setTitle(restaurantInfo.getCg_name());
        tvAddress.setText(restaurantInfo.getCg_addr());
        tvOpenTime.setText(restaurantInfo.getCg_openst() + "~" +
                restaurantInfo.getCg_openet());
        tvDeliverMealsTime.setText(TextUtils.isEmpty(restaurantInfo.getCg_sendst()) && TextUtils.isEmpty(restaurantInfo.getCg_sendet()) ? "（暂不支持）" : restaurantInfo.getCg_sendst() + "~" +
                restaurantInfo.getCg_sendet());
        if (TextUtils.isEmpty(restaurantInfo.getCg_sendst()) && TextUtils.isEmpty(restaurantInfo.getCg_sendet())) {
            llAboutmoney.setVisibility(View.GONE);
            //当店铺不支持送餐的时候 外送按钮为灰色
            btTakeaway.setEnabled(false);
            btTakeaway.setBackgroundResource(R.color.gray);
        } else {
            tvGotomoney.setText("   满￥" + restaurantInfo.getCg_lowlimit() + "免运费");
            tvGomoney.setText("送餐费:￥" + restaurantInfo.getCg_shipping());
        }
        getSellMessage();

    }

    // TODO: 2016/10/11  更改此处地址指向
    private void getSellMessage() {
        restaurantPageP.addData(Model.HTTPURL + Model.NEWGETOFF + "cgid=" + cgid);
    }

    private void addData() {
        restaurantPageP.getCgMessage(Model.HTTPURL + Model.RESTAURANT + "cgid=" + cgid);
    }

    @Override
    public void sendRestaurantInfo(RestaurantInfo restaurantInfo) {
        if (restaurantInfo != null) {
            this.restaurantInfo = restaurantInfo;
            bundle.putSerializable(Constants.RESTAURANT, restaurantInfo);
            initMessage();
        }
    }

    @Override
    public void sendLists(List<CardInfo> cardInfos, List<IntegralInfo> integralInfos, List<TopupInfo>
            topupInfos, List<PromotionsInfo> promotionsInfos) {
        this.cardInfos = cardInfos;
        this.integralInfos = integralInfos;
        this.topupInfos = topupInfos;
        this.promotionsInfos = promotionsInfos;
        if (cardInfos.size() != 0) {
            cardInfoContent.setText("消费" + cardInfos.get(0).getCard_upperlimit() + "返"
                    + cardInfos.get(0).getCard_value() +
                    "，每消费" + cardInfos.get(0).getCard_givelimit() + "元可获取");
        }
        if (topupInfos.size() != 0) {
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < topupInfos.size(); i++) {
                buffer.append("交" + topupInfos.get(i).getReceipt_money() + "充" + topupInfos.get(i).getAdd_money());
                if (i != topupInfos.size() - 1 && topupInfos.size() > 1) {
                    buffer.append(",");
                } else {
                    buffer.append("。");
                }
            }
            topupInfoContent.setText(buffer.toString());
        }
        if (promotionsInfos.size() != 0) {
            tvOffers.setText(promotionsInfos.get(promotionsInfos.size()-1).getProm_info());
        }
        if (integralInfos.size() != 0) {
            tvScore.setText(integralInfos.get(0).getMember_integral() + "积分可以兑换" +
                    integralInfos.get(0).getDishes_name());
        }


    }

    @Override
    public void showdialog() {
        showDialog();
    }

    @Override
    public void dissmissdialog() {
        dissMissDialog();
    }

    // TODO: 2016/10/11 完成后添加项目的 登录跳转 
    @OnClick({R.id.bt_Takeaway, R.id.bt_shopfororder, R.id.sale_layout, R.id.sorce_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_Takeaway:
//                toast("外卖");
                if (getBoolean(Constants.ISLOGIN)) {
                    isVIP();
                    bundle.putInt(Constants.TYPE, 1);
                    startActivity(OrderActivity.class, bundle);
                } else {
                    toLogin();
                }
                break;
            case R.id.bt_shopfororder:
                if (getBoolean(Constants.ISLOGIN)) {
                    isVIP();
                    bundle.putInt(Constants.TYPE, 0);
                    startActivity(OrderActivity.class, bundle);
                } else {
                    toLogin();
                }

                break;
            case R.id.sale_layout:
                if (promotionsInfos.size() != 0) {
                    bundle.putSerializable(Constants.PROMOTIONSLIST, (Serializable) promotionsInfos);
                    startActivity(SaleActivity.class, bundle);
                }
                break;
            case R.id.sorce_layout:
                if (integralInfos.size() != 0) {
                    bundle.putSerializable(Constants.INTEGRAL, (Serializable) integralInfos);
                    startActivity(ScoresActivity.class, bundle);
                }
                break;
            case R.id.iv_callPhone:
                RestaurantPageActivityPermissionsDispatcher.onSuccedWithCheck(this);
                break;
        }
    }

    private void toLogin() {
        new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                .setTitleText("请先登录")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        Intent intent =new Intent();
                        intent.putExtra(Constants.TAG,context.getClass().getName());
                        intent.setClass(context,LoginActivity.class);
                        startActivity(intent);
                    }
                }).show();
    }

    private void callPhone() {
        new SweetAlertDialog(RestaurantPageActivity.this, SweetAlertDialog.NORMAL_TYPE)
                .setTitleText(restaurantInfo.getCg_name())
                .setContentText("电话:" + restaurantInfo.getCg_phone())
                .setConfirmText("拨打")
                .setCancelText("取消")
                .setCustomImage(R.mipmap.u412)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + restaurantInfo.getCg_phone()));
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        startActivity(intent);
                        sweetAlertDialog.dismiss();
                    }
                })
                .showCancelButton(true)
                .show();
    }



    private void isVIP() {
        String url = Model.HTTPURL + Model.TOVIP + "cgid=" + cgid + "&cgname=" + restaurantInfo.getCg_name() + "&userPhone=" +
                getString(Constants.USERPHONE) + "&userID=" + getString(Constants.BAIDUUSERID)
                + "&channelID=" + getString(Constants.BAIDUCHANGEID) + "&deviceID=" + "&deviceID=" +
                getString(Constants.DEVID);
        restaurantPageP.addToVip(url);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Activity&从堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void onSucced() {
        callPhone();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RestaurantPageActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void onCause(final PermissionRequest request) {
        giveMsg(request);
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void onBreak() {
        showHelp();
    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void onNever() {
        showHelp();
    }

    private void showHelp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }
    private void giveMsg(PermissionRequest request) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("应用运行拨打电话的权限。请许可授权");
        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                request.proceed();
            }
        });

        builder.setCancelable(false);
        builder.show();
    }
}
